<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">{{ t('sys.configuration.add') }}</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label:  t('sys.script.Distributionlog'),
                tooltip:  t('sys.script.Distributionlog'),
                onClick: handleEditRemark.bind(null, record),
              },

              {
                label: t('sys.configuration.edit'),
                tooltip: t('sys.configuration.edit'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: t('sys.script.download'),
                tooltip: t('sys.script.downloadFile'),
                onClick: handleDownload.bind(null, record),
              },
              {
                label: t('sys.script.details'),
                tooltip: t('sys.script.details'),
                onClick: handleOtherVersions.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <OtherVersionsModal @register="registerOtherVersionsModal" @success="handleSuccessOther" />
    <EditRemarkModal @register="registerEditRemarkModal" @success="handleRemarkSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watch } from 'vue';
  import { useModal } from '@/components/Modal';
  import { message } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getScriptsPageAPI } from '@/api/demo/script';
  import { PageWrapper } from '@/components/Page';
  import { columns } from './account.data';
  import { useGo } from '@/hooks/web/usePage';
  import AccountModal from './AccountModal.vue';
  import OtherVersionsModal from './OtherVersionsModal.vue';
  import EditRemarkModal from './EditRemarkModal.vue';
  import { useWebSocketStore } from '@/store/modules/websocket';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  const webSocketStore = useWebSocketStore();

  defineOptions({ name: 'AccountManagement' });
  const total = ref(0);

  const tableTitle = computed(() => `${t('sys.script.details')} ${t('sys.configuration.common')} ${total.value} ${t('sys.configuration.strip')}`);
  const go = useGo();
  const searchInfo = reactive<Recordable>({});
  const [registerModal, { openModal }] = useModal();
  const [registerOtherVersionsModal, { openModal: openOtherVersionsModal }] = useModal();
  const [registerEditRemarkModal, { openModal: openEditRemarkModal }] = useModal();
  const [registerTable, { reload, updateTableDataRecord }] = useTable({
    title: tableTitle,
    api: async (params) => {
      const result = (await getScriptsPageAPI(params)) as { items: any[]; total: number };
      total.value = result.total;
      return result;
    },
    rowKey: 'id',
    columns,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 250,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
    },
  });

  function handleView(record: Recordable) {
    go('/system/account_detail/' + record.id);
  }

  function handleCreate(record) {
    openModal(true, {
      record,
      isUpdate: false,
    });
  }

  function handleOtherVersions(record) {
    openOtherVersionsModal(true, {
      record,
    });
  }

  function handleEdit(record) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      const result = updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }

  function handleSuccessOther({ isUpdate, values }) {
    reload();
  }
  function handleRemarkSuccess() {
    reload(); // 刷新表格数据
  }

  function handleEditRemark(record) {
    openEditRemarkModal(true, {
      record,
    });
  }
  async function handleDownload(record) {
    try {
      const response = await fetch(record.filePath);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('下载文件时出错:', error);
    }
  }

  // 监听 webSocketStore 中的 state 变化
  // watch(
  //   () => webSocketStore.$state,
  //   (newState, oldState) =>
  //     // 在这里可以执行一些操作，例如更新表格数据
  //   },
  //   { deep: true },
  // );
</script>
